package com.imooc.springmvc.controller;

import com.imooc.springmvc.entity.User;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.Date;

@Controller
@RequestMapping("/um")
public class URLMappingController {
    @GetMapping("/g")
    @ResponseBody
    public String getMapping(@RequestParam("manager_name") String managerName, Date createTime) {
        System.out.println("manager_name: " + managerName);
        return "This is a GET request";
    }

    @PostMapping("/p")
    @ResponseBody
    public String postMapping(String username,Long password) {
        System.out.println("username: " + username);
        System.out.println("password: " + password);
        return "This is a POST request";
    }
    @PostMapping("/po")
    @ResponseBody
    public String postMappingObject(User user, String username,@DateTimeFormat(pattern = "yyyy-MM-dd") Date createTime) {
        System.out.println("username: " + user.getUsername());
        System.out.println("password: " + user.getPassword());
        return "This is a POST request";
    }
    @GetMapping("/view")
    public ModelAndView showView(Integer userId) {
        ModelAndView mav = new ModelAndView("/view.jsp");
        User user = new User();
        if (userId == 1) {
            user.setUsername("lily");
        }else if (userId == 2) {
            user.setUsername("lucy");
        }
        mav.addObject("u", user);
        return mav;
    }

    /**
     * String与ModelMap
     * Controller方法返回String的情况
     * 1、方法被@ResponseBody描述，SpringMvc直接响应String字符串本身
     * 2、方法不存在@ResponseBody，则SpringMVC处理String指代的视图（页面）
     * @param userId
     * @param modelMap
     * @return
     */
    @GetMapping("/view1")
    public String showView1(Integer userId, ModelMap modelMap) {
        String view = "/um/view.jsp";
        User user = new User();
        if (userId == 1) {
            user.setUsername("lily");
        }else if (userId == 2) {
            user.setUsername("lucy");
        }
        modelMap.addAttribute("u", user);
        return view;
    }
}
